package com.osmp.web.user.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.osmp.web.base.core.SystemConstant;
import com.osmp.web.user.dao.RoleMapper;
import com.osmp.web.user.dao.UserMapper;
import com.osmp.web.user.entity.Role;
import com.osmp.web.user.entity.User;
import com.osmp.web.user.entity.UserRole;
import com.osmp.web.user.service.UserService;
import com.osmp.web.utils.DataGrid;
import com.osmp.web.utils.Md5Encode;
import com.osmp.web.utils.Pagination;
import com.osmp.web.utils.RequestUtils;
import com.osmp.web.utils.Utils;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RoleMapper roleMapper;

	@RequestMapping("/toList")
	public String getUser() {
		return "user/userList";
	}

	@RequestMapping("/userList")
	@ResponseBody
	public Map<String, Object> userList(DataGrid dg) {
		Pagination<User> p = new Pagination<User>(dg.getPage(), dg.getRows());
		List<User> list = userService.selectAll(p, "");
		dg.setResult(list);
		dg.setTotal(p.getTotal());
		return dg.getMap();
	}

	@RequestMapping("/toAdd")
	public String toAdd() {
		return "user/userAdd";
	}

	@RequestMapping("/saveOrUpdateUser")
	@ResponseBody
	public Map<String, Object> saveOrUpdate(HttpServletRequest request) {
		User user = RequestUtils.getEntity(User.class, request);
		try {
			String password = user.getPassword();
			password = Md5Encode.encodeByMD5(password).toUpperCase();
			user.setPassword(password);
			if (StringUtils.isEmpty(user.getId())) {
				user.setId(UUID.randomUUID().toString());
				user.setCreateTime(Utils.dateToString(new Date()));
				userMapper.insert(user);
			} else {
				User u = userMapper.getById(user.getId());
				user.setCreateTime(u.getCreateTime());
				userMapper.update(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return RequestUtils.ERROR();
		}
		return RequestUtils.SUCCESS();
	}

	@RequestMapping("/toRoleList")
	public String getRole() {
		return "user/roleList";
	}

	@RequestMapping("/roleList")
	@ResponseBody
	public Map<String, Object> roleList(DataGrid dg) {
		Pagination<Role> p = new Pagination<Role>(dg.getPage(), dg.getRows());
		List<Role> list = roleMapper.selectByPage(p, Role.class, "");
		dg.setResult(list);
		dg.setTotal(p.getTotal());
		return dg.getMap();
	}

	@RequestMapping("/toRoleAdd")
	public String toRoleAdd() {
		return "user/roleAdd";
	}

	@RequestMapping("/saveOrUpdateRole")
	@ResponseBody
	public Map<String, Object> saveOrUpdateRole(HttpServletRequest request) {
		Role role = RequestUtils.getEntity(Role.class, request);
		try {
			if (StringUtils.isEmpty(role.getId())) {
				role.setId(UUID.randomUUID().toString());
				roleMapper.insert(role);
			} else {
				roleMapper.update(role);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return RequestUtils.ERROR();
		}
		return RequestUtils.SUCCESS();
	}

	@RequestMapping("/toEditUser")
	public ModelAndView toEditUser(String id) {
		ModelAndView mav = new ModelAndView("user/edit");
		User user = userService.getUserById(id);
		mav.addObject("user", user);
		return mav;
	}

	@RequestMapping("/toAddRole")
	public ModelAndView toAddRole(String id) {
		ModelAndView mav = new ModelAndView("user/addRole");
		mav.addObject("userId", id);
		return mav;
	}

	@RequestMapping("/toGetUserRole")
	public ModelAndView toGetUserRole(String id) {
		ModelAndView mav = new ModelAndView("user/getUserRole");
		mav.addObject("userId", id);
		return mav;
	}

	@RequestMapping("/ajaxAddUserRole")
	@ResponseBody
	public Map<String, Object> ajaxAddUserRole(@RequestParam("id") String id,
			@RequestParam("roleIds") String[] roleIds) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<String> lis = userMapper.selectUserRole(id);
			if (this.isIdsequals(lis, roleIds)) {
				map.put("success", true);
				map.put("msg", "鎿嶄綔鎴愬姛");
				return map;
			}
			userService.deletByUserId(id);
			if (Utils.contains(roleIds, SystemConstant.ADMIN_ROLE_ID)) {
				UserRole ur = new UserRole();
				ur.setId(UUID.randomUUID().toString());
				ur.setUserId(id);
				ur.setRoleId(SystemConstant.ADMIN_ROLE_ID);
				userMapper.addUserRole(ur);
				map.put("success", true);
				map.put("msg", "鎿嶄綔鎴愬姛");
				return map;
			}
			for (String integer : roleIds) {
				UserRole ur = new UserRole();
				ur.setId(UUID.randomUUID().toString());
				ur.setUserId(id);
				ur.setRoleId(integer);
				userMapper.addUserRole(ur);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "添加成功");
			return map;
		}
		map.put("success", true);
		map.put("msg", "添加失败");
		return map;
	}

	@RequestMapping("/deleteUser")
	@ResponseBody
	public Map<String, Object> testDel(User p) {
		try {
			userService.deletUser(p);
		} catch (Exception e) {
			return RequestUtils.ERROR();
		}
		return RequestUtils.SUCCESS();
	}

	/**
	 * 
	 * @param ids
	 * @param roleIds
	 * @return
	 */
	private boolean isIdsequals(List<String> ids, String[] roleIds) {
		if (ids != null && roleIds.length == ids.size()) {
			for (int i = 0; i < roleIds.length; i++) {
				if (ids.contains(roleIds[i])) {
					continue;
				} else {
					return false;
				}
			}
			return true;
		}
		return false;
	}

}
